/**
 * @description: 定义班级 service
 * @version: 0.0.1
 * @author: z..
 * @Date: 2023-06-12 18:16:39
 */

import { Provide } from '@midwayjs/core';
import { RobotAlarmLogs } from './robot_alarm_logs.entity';

import { InjectRepository, InjectDataSource } from '@midwayjs/sequelize';
import { Repository, Sequelize } from 'sequelize-typescript';

@Provide()
export class RobotAlarmLogsModel {

  @InjectRepository(RobotAlarmLogs)
  RobotAlarmLogsRepository: Repository<RobotAlarmLogs>;

  @InjectDataSource()
  SequelizeQuery: Sequelize;

  /**
    * 分页查询获取总条数
    * @returns 
    */
  async getTotalNum(): Promise<any> {
    const sql = `SELECT count(1) as num from robot_alarm_logs;`;
    const [results] = await this.SequelizeQuery.query(sql);
    return results;
  }

  /**
   * 分页查询获取列表
   * @param {*} pageNum 
   * @param {*} pageSize
   * @param {*} searchKey
   * @returns 
   */
  async getDataByPage(pageNum: number, pageSize: number, searchKey: any): Promise<any> {
    const _limit = (pageNum - 1) * pageSize;
    const sql = `SELECT * FROM robot_alarm_logs where ORDER BY created_at DESC LIMIT ${_limit},${pageSize};`;
    const [results] = await this.SequelizeQuery.query(sql);
    return results;
  }

  /**
   * 新增任务通知日志
   * @param {*} alarmId 
   * @param {*} logName 
   * @param {*} logData 
   * @returns 
   */
  async createAlarmLogs(params: any): Promise<any> {
    const sql = `INSERT INTO robot_alarm_logs 
    SET alarm_id = ${params.alarmId},
    log_name = '${params.logName}',
    log_data = '${params.logData}',
    created_at = now(),
    updated_at = now();`;
    const [results] = await this.SequelizeQuery.query(sql);
    return results;
  }

  /**
  * 根据id查询任务通知日志
  * @param {*} id
  * @returns 
  */
  async getAlarmLogsById(id: number): Promise<any> {
    const sql = `select * from robot_alarm_logs WHERE alarm_id = ${id}`;
    const [results] = await this.SequelizeQuery.query(sql);
    return results;
  }

  /**
   * 删除一周前的日志
   * @returns 
   */
  async delWeekagoLogs(): Promise<any> {
    const sql = 'DELETE FROM robot_alarm_logs WHERE created_at < DATE_SUB(NOW(), INTERVAL 1 WEEK);';
    const [results] = await this.SequelizeQuery.query(sql);
    return results;
  }

}